package WarTug;

/** NoobMarcusHandler.java */

import java.util.ArrayList;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

public class InputHandler {
	
	private ArrayList<Button> buttonList;
	private TextField activeField = null;
	private boolean mouseDown = false;
	
	public InputHandler(ArrayList<Button> buttonList){
		this.buttonList = buttonList;
	}
	
	public InputHandler(){
		this(null);
	}
	
	public void handleKeyboard(WarTug game){
		if (game.currentScreen == Screen.inGame){
			while (Keyboard.next()){
				if (Keyboard.getEventKeyState()) {
					if (Keyboard.getEventKey() == Keyboard.KEY_C){
						if (game.debug){
							game.network.sendClearUnitsRequest();
						}
					}
				}
			}
		}
		// First make sure there is something to add text to
		if (activeField != null){
			while (Keyboard.next()){
				if (Keyboard.getEventKeyState()) {
					// Give the typed character to the active TextField
					activeField.addChar(Keyboard.getEventKey(), Keyboard.getEventCharacter());
				}
			}
		} else
			Keyboard.next();
	}
	
	public void handleMouse(WarTug game){
		// Pressing the left mouse button
		if (!mouseDown && Mouse.isButtonDown(0)){
			boolean textFieldClicked = false;
			mouseDown = true;
			int x = Mouse.getX();
			int y = GraphicsManager.WINDOW_HEIGHT - Mouse.getY(); // Have to invert the y coordinate.  0 is at the bottom...
			//System.out.println("x: " + x + " y: "+ y);
			for (Button b: buttonList){
				// Try to perform a click on each button
				boolean clicked = false;
				if (b.act != null)
					clicked = b.takeClick(x, y);
				// If successfully clicked, then handle the focusing of text fields
				if (clicked && b instanceof TextField){
					activeField = (TextField) b;
					textFieldClicked = true;
				}
			}
			if (game.currentScreen == Screen.inGame){
				// Checking your garden selection clicks
				Garden gard = game.getGardenEntity().garden;
				int relX = x - gard.GARDEN_SCREEN_X;
				int relY = y - gard.GARDEN_SCREEN_Y;
				if (relY >= 0 && relX >= 0){
					game.getGardenEntity().garden.handleClick(relX, relY, game.getGardenEntity().buttons);
					
				}
				// Checking your garden options clicks
				relX = x - game.gOpts.SCREENX;
				relY = y - game.gOpts.SCREENY;
				if (relY >= 0 && relX >= 0){
					game.gOpts.handleClick(relX, relY, game);
				}
				
			}
			if (!textFieldClicked){
				activeField = null;
			}
		} else if (mouseDown && !Mouse.isButtonDown(0)){
			mouseDown = false;
		}
	}
	
	public ArrayList<Button> getButtonList(){
		return buttonList;
	}
	
	public void setButtonList(ArrayList<Button> newButtons){
		buttonList = newButtons;
	}
	
	public void clearButtonList(){
		buttonList = null;
		activeField = null;
	}
	
	
	
}
